from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.crud.user_config import user_config
from app.schemas.user_config import UserConfigCreate, UserConfigUpdate, UserConfigResponse
from loguru import logger

router = APIRouter()

@router.get("/", response_model=UserConfigResponse)
async def get_config(db: Session = Depends(get_db)):
    """获取用户配置"""
    try:
        config = user_config.get_default_config(db)
        return config
    except Exception as e:
        logger.error(f"获取配置失败: {str(e)}")
        raise HTTPException(status_code=500, detail="获取配置失败")

@router.post("/", response_model=UserConfigResponse)
async def create_config(
    config_in: UserConfigCreate,
    db: Session = Depends(get_db)
):
    """创建用户配置"""
    try:
        config = user_config.create(db, obj_in=config_in)
        return config
    except Exception as e:
        logger.error(f"创建配置失败: {str(e)}")
        raise HTTPException(status_code=500, detail="创建配置失败")

@router.put("/", response_model=UserConfigResponse)
async def update_config(
    config_in: UserConfigUpdate,
    db: Session = Depends(get_db)
):
    """更新用户配置"""
    try:
        current_config = user_config.get_default_config(db)
        config = user_config.update(db, db_obj=current_config, obj_in=config_in)
        return config
    except Exception as e:
        logger.error(f"更新配置失败: {str(e)}")
        raise HTTPException(status_code=500, detail="更新配置失败")

@router.put("/theme", response_model=UserConfigResponse)
async def update_theme(theme: str, db: Session = Depends(get_db)):
    """更新主题设置"""
    try:
        config = user_config.update_theme(db, theme=theme)
        return config
    except Exception as e:
        logger.error(f"更新主题失败: {str(e)}")
        raise HTTPException(status_code=500, detail="更新主题失败") 